package com.example.forum.service.impl;
/* @Author      zouzh
 * @PackageName forum
 * @Package     com.example.forum.service.impl
 * @Date        2023/9/17 3:47
 */

import com.example.forum.Utils.StringUtils;
import com.example.forum.common.AppResult;
import com.example.forum.common.ResultCode;
import com.example.forum.dao.ArticleMapper;
import com.example.forum.exception.ApplicationException;
import com.example.forum.model.Article;
import com.example.forum.model.Board;
import com.example.forum.model.User;
import com.example.forum.service.IArticleService;
import com.example.forum.service.IBoardService;
import com.example.forum.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class ArticleServiceImpl implements IArticleService {

    @Autowired
    private ArticleMapper articleMapper;

    // 用户和板块的操作
    @Autowired
    private IUserService userService;
    @Autowired
    private IBoardService boardService;
    @Override
    public void creat(Article article) {
        // 非空校验
        if (article == null  || article.getUserId() == null ||
                article.getBoardId() == null ||
                StringUtils.isEmpty(article.getTitle()) ||
                StringUtils.isEmpty(article.getContent())){
            // 打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        // 设置默认值
        article.setLikeCount(0);
        article.setVisitCount(0);
        article.setReplyCount(0);
        article.setDeleteState((byte) 0);
        article.setState((byte) 0);
        Date date = new Date();
        article.setCreateTime(date);
        article.setUpdateTime(date);
        // 写入数据库
        int articleRow = articleMapper.insertSelective(article);
        if (articleRow <= 0){
            // 打印日志
            log.warn(ResultCode.FAILED_CREATE.toString());
            // 抛出异常
            throw  new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }
        // 获取用户信息
        User user = userService.selectById(article.getUserId());
        // 判断 用户信息是否有效
        if (user == null){
            // 打印日志
            log.warn(ResultCode.FAILED_CREATE.toString() + ", 发贴失败, user id = " + article.getUserId());
            // 抛出异常
            throw  new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }
        // 更新用户的发帖数
        userService.addOneArticleCountByID(user.getId());

        // 获取板块信息
        Board board = boardService.selectById(article.getBoardId());
        if (board == null){
            // 打印日志
            log.warn(ResultCode.FAILED_CREATE.toString() + ", 发贴失败, board id = " + article.getBoardId());
            // 抛出异常
            throw  new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }

        // 更新板块中的帖子数量
        boardService.addOneArticleCountByID(board.getId());

        // 打印日志
        log.info(ResultCode.SUCCESS.toString() + ", user id = " + article.getUserId()
                + ", board id = " + article.getBoardId() + ", article id = "+article.getId() + "发帖成功");

    }

    @Override
    public List<Article> selectAll() {
        // 调用 dao
        List<Article> articles = articleMapper.selectAll();
        // 返回结果
        return articles;

    }

    @Override
    public List<Article> selectAllByBoardId(Long boardId) {
        // 校验参数
        if (boardId == null || boardId <= 0){
            // 打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 打印日志
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 检验板块是否存在
        Board board = boardService.selectById(boardId);
        if (board == null) {
            log.warn(ResultCode.FAILED_BOARD_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_BOARD_NOT_EXISTS));
        }
        // 调用 dao
        List<Article> articles = articleMapper.selectAllByBoardId(boardId);
        return articles;


    }

    @Override
    public Article selectById(Long id) {
        // 校验参数
        if (id == null || id <= 0){
            // 打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 调用 mapper
        Article article = articleMapper.selectByPrimaryKey(id);
        // 返回结果
        return article;
    }

    @Override
    public Article selectDetailById(Long id) {
        // 校验参数
        if (id == null || id <= 0){
            // 打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 调用 mapper
        Article result = articleMapper.selectDetailById(id);
        if (result == null){
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        // 构造更新文章数据对象
        Article update = new Article();
        update.setId(result.getId());
        update.setVisitCount(result.getVisitCount() + 1);
        int row = articleMapper.updateByPrimaryKeySelective(update);
        if (row != 1){
            log.info(ResultCode.ERROR_SERVICES.toString() + "articleId = " + result.getId());
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }

        result.setVisitCount(result.getVisitCount() +1);
        return result;
    }

    @Override
    public List<Article> selectByUserId(Long userId) {
        // 校验参数
        if (userId == null || userId <= 0){
            // 打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 打印日志
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 检验用户是否存在
        User user = userService.selectById(userId);
        if (user == null){
            // 打印日志
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            // 打印日志
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        // 调用 dao
        List<Article> articles = articleMapper.selectByUserId(userId);

        return articles;
    }


    @Override
    public void modify(Long id, String title, String content) {
        if (id == null || id <= 0 || StringUtils.isEmpty(title) || StringUtils.isEmpty(content)){
            // 打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 构造修改对象
        Article article = new Article();
        article.setId(id);
        article.setTitle(title);
        article.setContent(content);
        article.setUpdateTime(new Date());
        int i = articleMapper.updateByPrimaryKeySelective(article);
        if (i != 1){
            // 打印日志
            log.warn(ResultCode.ERROR_SERVICES.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }

    }

    @Override
    public void thumbsUp(Long id) {
        // 非空校验
        if (id == null || id <= 0){
            // 打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 获取原始帖子详情
        Article article = articleMapper.selectByPrimaryKey(id);
        // 帖子不存在
        if (article == null || article.getDeleteState() == 1 ){
            // 打印日志
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        // 帖子状态异常
        if ( article.getState() == 1){
            // 打印日志
            log.warn(ResultCode.FAILED_ARTICLE_BANNED.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED));
        }
        // 构造更新对象
        Article updateArticle = new Article();
        updateArticle.setId(id);
        updateArticle.setLikeCount(article.getLikeCount() + 1);
        int i = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if (i != 1){
            // 打印日志
            log.warn(ResultCode.ERROR_SERVICES.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
    }

    @Override
    public void deleteById(Long id) {
        // 非空校验
        if (id == null || id <= 0){
            // 打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 获取原始帖子详情
        Article article = articleMapper.selectByPrimaryKey(id);
        // 帖子不存在
        if (article == null || article.getDeleteState() == 1 ){
            // 打印日志
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        // 构造更新对象
        Article updateArticle = new Article();
        updateArticle.setId(article.getId());
        updateArticle.setDeleteState((byte) 1);
        // 调用 dao
        int i = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if (i != 1){
            // 打印日志
            log.warn(ResultCode.ERROR_SERVICES.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
        // 更新板块中的帖子数量
        boardService.subOneArticleCountById(article.getBoardId());
        // 更新用户发帖数
        userService.subOneArticleCountById(article.getUserId());
        log.info("删除帖子成功，articleId = " + article.getId());
    }

    @Override
    public void addOneReplyCountById(Long id) {
        if (id == null || id <= 0){
            // 打印日志
            log.warn(ResultCode.FAILED_BOARD_ARTICLE_COUNT.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_BOARD_ARTICLE_COUNT));
        }
        // 查询对应的板块
        Article article = articleMapper.selectByPrimaryKey(id);
        if (article == null || article.getDeleteState() == 1){
            // 打印日志
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        if (article.getState() == 1){
            // 打印日志
            log.warn(ResultCode.FAILED_ARTICLE_BANNED.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED));
        }
        // 更新帖子的数量
        Article updateArticle = new Article();
        updateArticle.setId(article.getId());
        updateArticle.setReplyCount(article.getReplyCount() + 1);
        // 更新数据库
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        // 判断受影响的行数
        if (row != 1){
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
    }

}
